#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 说明：自行将中英文混合文本按照中文、英文分段处理，全部使用`onnx`模式合成语音数据，然后按照原有顺序拼接起来。
# 速度快。
from funasr import AutoModel
import sys,os
from flask import Flask, request, abort

model = AutoModel(model="paraformer-zh",  
                  vad_model="fsmn-vad", 
                  vad_kwargs={"max_single_segment_time": 60000},
                  punc_model="ct-punc", 
                  )
                  
def textJoin( text ):
    res = []
    for item in text:
        res.append(item['text'])
    return '，'.join(res)

if len(sys.argv) == 2:
    text = model.generate(input=sys.argv[1])
    print(textJoin(text))
    f = open("/tmp/funasr-ok",'w')
    f.write('ok\n')
    f.close()
    #print('，'.join(text) + "\n")

app = Flask("__name__")

@app.route("/api/asr", methods=["POST"])
def api_tts():
    name = request.form['name'].strip()
    if len(name)==0:
        return abort(404)
    if False == name.endswith(".wav"):
            return "?\n"
    try:
      info = os.stat(name)
      if info == None:
            return "?\n"
      if info.st_size > 400000:
            return abort(404)
    except:
         return "?\n"
    print("wav:"+name + "\n")
    try:
        text = model.generate(input=name)
        #return result
        return textJoin(text)
    except:
        print(sys.exc_info())
        return "?\n"

if __name__ == '__main__':
    try:
        app.run(host="localhost", port=15060)
    except:
        print(sys.exc_info())
        print("崩溃\n")
    os.unlink("/tmp/funasr-ok")